package com.woniu.sharepark.common.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.woniu.sharepark.common.JsonResult;
import com.woniu.sharepark.common.pojo.Login;
import com.woniu.sharepark.common.pojo.UserInfo;
import com.woniu.sharepark.common.service.UserInfoService;
import com.woniu.sharepark.common.service.UserService;
import com.woniu.sharepark.leasesystem.common.pojo.DrivingPermit;
import com.woniu.sharepark.leasesystem.common.service.DrivingPermitService;
import com.woniu.sharepark.platformsystem.log.annonation.BackgroundLogAnnotation;
import com.woniu.sharepark.util.PictureUtil;
import com.woniu.sharepark.util.RealIdCard;
import com.woniu.sharepark.util.VerificationCodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author:rhc
 * @date: 2019/6/4
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private DrivingPermitService drivingPermitService;
    @Value("${file.address}")
    private String filePath;
    @Autowired
    private UserInfoService userInfoService;
    /**
     *@Description: 发送短信验证码
     *@Param: [phoneNumber]手机电话号码
     *@return: com.woniu.sharepark.common.JsonResult
     *@Author: rhc
     *@date: 2019/6/5
     */
   @RequestMapping("/sendVerification")
   @ResponseBody
    public JsonResult sendVerification(String phoneNumber) throws ClientException {
        //产生6位数验证码
       String code = VerificationCodeUtil.getMsgCode();
       //将验证码存入session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
       session.setAttribute("code",code);
       //发短信
        SendSmsResponse sendSmsResponse = VerificationCodeUtil.sendSms(phoneNumber, code);
       if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
           return JsonResult.ok("短信发送成功");
       }else {
            return JsonResult.error("短息发送失败,请检查手机号!");
        }
    }

    /**
     *@Description:注册功能
     *@Param: login 注册信息, code 验证码, rPassword 重复密码
     *@return: com.woniu.sharepark.common.JsonResult
     *@Author: rhc
     *@date: 2019/6/10
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    @BackgroundLogAnnotation(operate = "注册")
    public JsonResult register(Login login,String code,String rPassword,String invite) {
        JsonResult jsonResult = userService.register(login, code, rPassword,invite);
        return jsonResult;
    }

    @RequestMapping("/login")
    @ResponseBody
    @BackgroundLogAnnotation(operate = "登录")
    public JsonResult login(Login login) {
        // 1.交给shiro进行身份验证
        Subject subject = SecurityUtils.getSubject();
        // 创建token，放入账号密码
        UsernamePasswordToken token = new UsernamePasswordToken(login.getlAccount(), login.getlPassword());

        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            //账号不存在
            return JsonResult.error("登录失败，账号不存在!");
        }catch (IncorrectCredentialsException e){
            //密码错误
            return JsonResult.error("登录失败，密码不正确!");
        }catch (AuthenticationException e){
            //其他错误
            return JsonResult.error("未知错误，联系管理员");
        }
        //登录成功
        //登录成功保存session
        Login relLogin = userService.findUserByAccount(login.getlAccount());

        Session session = subject.getSession();
        session.setAttribute("currentUser",relLogin);
        return JsonResult.ok(""+relLogin.getrId());

    }

    /**
    * 登出
    * @title logout
    * @return java.lang.String
    * @author xin
    * @date 2019/6/21 17:58
    */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.html";
    }


   /**
   * 重置密码
   * @title resetPassword
   * @param oldPass 旧密码
   * @param newPass 新密码
   * @return com.woniu.sharepark.common.JsonResult
   * @author xin
   * @date 2019/6/12 16:54
   */
    @RequestMapping("/resetPassword")
    @ResponseBody
    @BackgroundLogAnnotation(operate = "修改密码")
    public JsonResult resetPassword(@RequestParam("oldPass") String oldPass, @RequestParam("newPass") String newPass){

        // 获取当前账户
        Subject subject=SecurityUtils.getSubject();
        Session session=subject.getSession();
        Login login=(Login) session.getAttribute("currentUser");


        oldPass=new SimpleHash("MD5",oldPass,login.getlAccount(),2).toString();

        if (oldPass.equals(login.getlPassword())){

            newPass=new SimpleHash("MD5",newPass,login.getlAccount(),2).toString();
            login.setlPassword(newPass);
            if (userService.resetPassword(login)>0){
                return JsonResult.ok("重置密码成功");
            }else {
                return JsonResult.ok("重置密码失败");
            }

        }else {
            return JsonResult.ok("旧密码错误");
        }

    }
    /**
    * 忘记密码
    * @title
    * @param phoneNum 手机号码
     * @param code 验证码
     * @param newPass 新密码
     * @param reNewPass 重复输入密码
    * @return com.woniu.sharepark.common.JsonResult
    * @author litong
    * @date 2019/6/20 14:45
    **/
    @RequestMapping("/forgetPass")
    @ResponseBody
    public JsonResult forgetPass(@RequestParam("phoneNum") String phoneNum,@RequestParam("code")String code,@RequestParam("newPass")String newPass,@RequestParam("reNewPass")String reNewPass){
        return userService.forgetPass(phoneNum,code,newPass,reNewPass);
    }
    @RequestMapping("/authentication")
    public ModelAndView authentication() {
        ModelAndView modelAndView = new ModelAndView("mobile/authentication");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        Login login = (Login) session.getAttribute("currentUser");
        modelAndView.addObject("user", login);
        DrivingPermit drivingPermit = drivingPermitService.findPermitByUid(login.getUserInfo().getuId());
        modelAndView.addObject("drivingPermit", drivingPermit);
        return modelAndView;
    }
    @RequestMapping("/idcard")
    @ResponseBody
    public JsonResult test(MultipartFile file) throws IOException {
        //获取图片名字
        String name = file.getOriginalFilename();
        //创建文件目录
        File nowFile = new File(filePath);
        if (!nowFile.exists()) {
            nowFile.mkdirs();
        }
        //生成文件名字
        String imgName = UUID.randomUUID().toString()+name;
        String nowPath = filePath + File.separator + imgName;
        //生成图片
        nowFile = new File(nowPath);
        file.transferTo(nowFile);
        //获取图片信息
        Map map = PictureUtil.getIdcardMsg(nowFile);
        String iDCard = (String) map.get("IDCard");
        String sex = (String) map.get("sex");
        String uname = (String) map.get("name");
        //判断图片是否有效
        if (iDCard.equals("") || iDCard == null ||sex.equals("") || sex == null||uname.equals("") || uname == null) {
            nowFile.delete();
            return JsonResult.error("请上传正确的身份证");
        }
        //判断身份证是否有效
        String json = RealIdCard.realId(uname, iDCard);
        if (!json.contains("实名认证通过！")) {
            return JsonResult.error("无效身份证");
        }
        //创建userInfo对象
        UserInfo userInfo = new UserInfo();
        userInfo.setuSex(sex);
        userInfo.setuName(uname);
        userInfo.setuCard(iDCard);
        //获取session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        //从session获取登陆信息
        Login login = (Login) session.getAttribute("currentUser");
        userInfo.setuId(login.getUserInfo().getuId());
        //上传身份信息
        userInfoService.updateUserInfo(userInfo);
        //再讲登陆信息存入session
        login = userService.findUserByAccount(login.getlAccount());
        session.setAttribute("currentUser",login);
        return JsonResult.ok();
    }


    /**
     * 添加物业账号信息
     * @title addCommunity
     * @param login 账号信息
     * @return com.woniu.sharepark.common.JsonResult
     * @author xin
     * @date 2019/6/15 15:50
     */
    @RequestMapping(value = "/addCommunity")
    @ResponseBody
    public JsonResult addCommunity(Login login) {

        return userService.addCommunity(login);

    }
}

